<template>
  <div class="layout-container">
    <div class="material-content ">
      <div class="box flex jc-sb ai-c ">
        <div class="phone-model flex jc-sb ai-c " @click="isShowPhoneModel = true">
          <div class="title">机型：</div>
          <div class="phone-select flex jc-sb ai-c">
            <div class="phone-name">{{ phoneModelName || '请选择机型' }}▼</div>
          </div>


        </div>
        <div class="material-name flex jc-fs ai-c " @click="isShowMaterial = !isShowMaterial">
          <img :src="frameImageUrl" style="width: 10vw;height: 5vh;"></img>
          <div class="text1">{{ materialName }}</div>
          <div class="text1">▼</div>

        </div>
      </div>
      <div class="material-list"   :style="{
        '--material-list-top': materialCount === 1 ? '100rpx' : materialCount === 2 ? '200rpx' : '300rpx','top': materialCount === 1 ? '100rpx' : materialCount === 2 ? '200rpx' : '300rpx'}"
       v-if="isShowMaterial">
       
        <div class="scroll-x">
          <van-radio-group v-model="activeMaterialIndex">

          
          <div class="scroll-container">
            <div class="material-item" v-for="item in normalMaterialList"  :key="item.id">
              <van-radio 
              :name="item.id"
              icon-size="25px"
               checked-color="#53D052"
              @click="selectMaterial(item, item.id)"
              >
                  <div class="images">
                    <van-image class="image-item" :src="item.baseImageUrl" mode="aspectFit"></van-image>
                    <van-image class="image-item" :src="item.frameImageUrl" mode="aspectFit"></van-image>
                  </div>
                  <div class="title">
                    {{ item.name }}
                  </div>
              </van-radio>
            </div>
          </div>
          <div class="scroll-container">
            <div class="material-item" v-for="item in type103MaterialList" :key="item.id">
              <van-radio 
              :name="item.id"
              icon-size="25px"
              checked-color="#53D052"
              @click="selectMaterial(item, item.id)"
              >
            
              
                <div class="images" @click="selectMaterial(item, item.id)">
                  <van-image class="image-item" :src="item.baseImageUrl" mode="aspectFit"></van-image>
                  <van-image class="image-item" :src="item.frameImageUrl" mode="aspectFit"></van-image>
                </div>
                <div class="title">
                  {{ item.name }}
                </div>
              </van-radio>
            </div>
          </div>
          <div class="scroll-container">
            <div class="material-item" v-for="item in type104MaterialList" :key="item.id">
              <van-radio 
              :name="item.id"
              icon-size="25px"
              checked-color="#53D052"
              @click="selectMaterial(item, item.id)"
              >
            
              
                <div class="images" @click="selectMaterial(item, item.id)">
                  <van-image class="image-item" :src="item.baseImageUrl" mode="aspectFit"></van-image>
                  <van-image class="image-item" :src="item.frameImageUrl" mode="aspectFit"></van-image>
                </div>
                <div class="title">
                  {{ item.name }}
                </div>
              </van-radio>
            </div>
          </div>
          <div class="mask " style="" @click="isShowMaterial = false">

          </div>
          </van-radio-group>

        </div>
      </div>
    </div>
    <van-popup v-model:show="isShowPhoneModel"  position="bottom" :style="{ height: '50%' }">
      <van-picker ref="pickerRef" v-model="activePhoneModelId" title="" :columns="phoneModelList" @confirm="onConfirmPhoneModel" @cancel="onCancel" @change="onChange" />
    </van-popup>
    <!-- <van-popup v-model:show="isShowMaterial" position="top" :style="{ height: '30%' }">材质</van-popup> -->
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted,reactive,nextTick } from "vue";
import { PhoneAPI } from '@/request/api';
import { useUserStore } from '@/stores';
import { showSuccessToast,showFailToast  } from "vant";
import type { PickerInstance } from 'vant';
import 'vant/lib/toast/style';
import { i18n, setI18nLanguage } from "@/utils/languages";
import { useI18n } from "vue-i18n";
// import { i18n, useI18n, setI18nLanguage, langToNum } from '@star/languages';
const { t } = useI18n();
const pickerRef = ref<PickerInstance | null>(null);
// import usePopup from "@/hooks/usePopup";
// const { showLoadingToast, showSuccessToast, showFailToast } = usePopup();
import type {  MaterialListData,PhoneModelListData,VantPickerColumn } from "@/types/phoneInfo/index.ts";
type Column = {
  text: string;
  value: string;
};
type Props = {
  materialType?: string;
  materialList?: MaterialListData[];
};
const props = withDefaults(defineProps<Props>(),{
  materialType: "",
  materialList: () => [] as MaterialListData[] // 添加类型断言
});
const userStore = useUserStore();
const emit = defineEmits(["handleConfirmPhoneModel"]);
const show = ref<boolean>(false);
const isShowPhoneModel = ref<boolean>(false);
const isShowMaterial = ref<boolean>(false);
const baseImageUrl = ref<string>(''); // 基础图片URL
const frameImageUrl = ref<string>('https://dev-1313492473.cos.ap-guangzhou.myqcloud.com/sku/df4a514672934e499d8aa7a4b892ca8a.png'); // 机身图片URL
const phoneModelName = ref<string>('');
const materialName = ref<string>('镜面黑边');

interface MaterialWithIndex extends MaterialListData {
  i?: number;
}

const normalMaterialList = computed(() => {
  return (props.materialList || []).filter(i => 
    i.materialSubType !== 103 && 
    i.materialSubType !== 104
  );
});
const type103MaterialList = computed(() => {
  return (props.materialList || [])
    .filter(i => i.materialSubType === 103)
    .map((item, index) => ({
      ...item,
      i: 7 + index
    } as MaterialWithIndex));
});
const type104MaterialList = computed(() => {
  return (props.materialList || [])
    .filter(i => i.materialSubType === 104)
    .map((item, index) => ({
      ...item,
      i: 7 + index
    } as MaterialWithIndex));
});
const materialCount = computed(() => {
  console.log('materialCount',normalMaterialList.value.length,type103MaterialList.value.length,type104MaterialList.value.length);
  const hasArr1 = normalMaterialList.value.length > 0;
  const hasArr2 = type103MaterialList.value.length > 0;
  const hasArr3 = type104MaterialList.value.length > 0;
  return [hasArr1, hasArr2, hasArr3].filter(Boolean).length;
});
const activeMaterialIndex = ref<number>(1); // 当前选中的材质索引 
// const activePhoneModelId = ref<number>(35);//苹果16pro max
  const activePhoneModelId = ref<number[]>([0, 0]); 
let phoneModelList = ref<VantPickerColumn[]>([
//   [
//   {
//     name: "华为",
//     childrenList: [
//       { id: 36 , modelName: "" , name: "华为 MATE 60" },
//       { id: 37,  modelName: "", name: "华为 MATE 60 Pro" },
//     ],
//   },
//   {
//     name: "苹果",
//     childrenList: [
//       { id: 15,modelName: "", name: "苹果 11" },
//     ],
//   },
// ]
]);
const selectMaterial = (item: MaterialListData, id: number) => {
  activeMaterialIndex.value = id;
  materialName.value = item.name;
  frameImageUrl.value = item.frameImageUrl;
  // 可以添加其他处理逻辑...
};
const onConfirmPhoneModel = (value: any) => {
  console.log("onConfirm", value);
  isShowPhoneModel.value = false;
  // phoneModelName.value = value.selectedOptions
  //   .map((item: any) => item.text)
  //   .join('/');
  phoneModelName.value = value.selectedOptions[value.selectedOptions.length - 1].text;
  const selectedId = value.selectedOptions[value.selectedOptions.length - 1].id;
  userStore.setUserInfo({ phoneModelId: selectedId });// 更新用户信息
  emit("handleConfirmPhoneModel", value);
};
const onCancel = () => {
  isShowPhoneModel.value = false;
};
const onChange = (value: any) => {
  console.log("onChange", value);
};
const showPopup = () => {
  show.value = true;
};
const getPhoneModel = async() => { 
    // showLoadingToast({ message: '加载机型数据...', forbidClick: true });
    const response = await PhoneAPI.getphoneModel().catch(console.error);
    console.log('response',response);
    // 更新机型数据（根据实际接口返回结构调整）
    if (response) {
      const resData = response.data as PhoneModelListData[];
      // columns.value = response
      phoneModelList.value = resData.map((item: PhoneModelListData,parentIndex: number) => {
        return {
          text: item.name,
          value: parentIndex,
          id:parentIndex,
          children: item.childrenList.map((child: any,childIndex: number) => {
            return {
              modelName: child.modelName,
              text: child.name,
              value: childIndex,
              id: child.id,
              ...child,
            };
          }),
        };
      });
      nextTick(() => {
        // 新增：设置默认选中机型
        if (phoneModelList.value.length > 0) {
          findDefaultPhoneModel();
        }
      });
    }
    
 
};
const getMaterialList = async() => {
  const response = await PhoneAPI.getMaterialList().catch(console.error);
  console.log('getMaterialList',response);
}
// 在获取机型数据后添加以下逻辑
const findDefaultPhoneModel = () => {
  const targetId = userStore.userInfo.phoneModelId;
  console.log('targetId',targetId);
  // 新增：通过双循环查找缓存机型位置
  phoneModelList.value.forEach((parentItem, parentIndex) => {
    parentItem.children.forEach((childItem, childIndex) => {
      if (childItem.id === targetId) {
        // 找到后更新模型值和索引
        activePhoneModelId.value = [parentIndex, childIndex];
        phoneModelName.value = childItem.text;
      }
    });
  });
  // 无缓存时设置第一个机型为默认
  if (!targetId && phoneModelList.value.length > 0) {
    const firstChild = phoneModelList.value[0].children[0];
    activePhoneModelId.value = [0, 0];
    phoneModelName.value = firstChild.text;
    userStore.setUserInfo({ phoneModelId: firstChild.value });
  }
  console.log('activePhoneModelId',activePhoneModelId.value);
  console.log('phoneModelName',phoneModelName.value);
};
onMounted(async() => {
  await getPhoneModel();//获取手机型号数据
  // getMaterialList();//获取手机型材质数据
  
  // 默认选中第一个材质（示例选中type103的第一个）
  if (type103MaterialList.value.length > 0) {
    const firstMaterial = type103MaterialList.value[0];
    selectMaterial(firstMaterial, firstMaterial.id);
  }
});
</script>
<style lang="scss" scoped>
.material-content {
  display: flex;
  // padding: 10rpx;
  background-color: #fff;
  position: relative;
  .box{
    margin: 0 auto;
    width: 90vw;
  }
  .phone-model {
    height: 50rpx;
    line-height: 50rpx;
    font-size: 28rpx;
    position: relative;
    color: #979797;
    flex-shrink: 0;

    .phone-select {
      display: inline-block;
      border-radius: 50rpx;
      border: 2rpx solid #333;
      padding: 0 17rpx;
      font-size: 26rpx;
      height: 50rpx;

      text {
        font-weight: bold;
        color: #333;
      }

      .text1 {
        margin-left: 17rpx;
        font-size: 20rpx;
      }
    }
  }

  .material-name {
    height: 100rpx;
    display: flex;
    // flex-grow: 1;

    image {
      height: 100%;
      width: 100rpx;
      position: absolute;
    }

    text {
      font-size: 28rpx;
      margin: auto;
      margin-left: 100rpx;
    }

    .text1 {
      margin-left: 17rpx;
      font-size: 20rpx;
    }
  }

  .material-list {
    // width: 100vw;
    // overflow-y: hidden;

    // height: 600rpx;  // 增加弹出层高度
    // bottom: -600rpx;  // 增加弹出层高度

    //height: 300rpx;
    display: flex;
    flex-direction: column;
    width: 100%;
    background-color: #fff;
    position: absolute;
    // bottom: -300rpx;
    // left: 0;

    top: 100rpx; /* 基础间距 */
    // min-height: 300rpx;

    z-index: 999;
    box-shadow: -1rpx 10rpx 17rpx -7rpx #666;

    .mask{
      // border: 1px solid #333;
      height: 100vh;
      // height: calc(100vh - var(--material-list-top, 100rpx)); // 动态计算高度
      width: 100vw;
      position: fixed;
      // top: 300rpx; /* 基础间距 */
      top: var(--material-list-top, 100rpx); // 使用CSS变量
      // min-height: 300rpx;
      left: 0;
      // background-color: rgba(0,0,0,0.5);
      z-index: 998; // 设置遮罩层z-index比弹出层小
    }

    .scroll-x{
      width: 100vw;
      overflow-y: hidden;
      overflow-x: scroll;
        // 新增内容容器
      .scroll-container {
        gap: 20rpx;
        padding: 0 20rpx;
        width: 100vw;
        overflow-y: hidden;
        overflow-x: auto;
        display: flex;
        white-space: nowrap;
         /* 隐藏滚动条 */
          -ms-overflow-style: none;  /* IE和Edge */
          scrollbar-width: none;  /* Firefox */
          &::-webkit-scrollbar {
            display: none;  /* Chrome/Safari/Opera */
          }
      }
      .material-item{
        height: 280rpx;
        width: 180rpx;
        // border: 1px solid red;
        box-sizing: border-box;
        flex-shrink: 0;// 禁止弹性收缩
        // margin-right: 5rpx;

        :deep(.van-radio) {//添加深度选择器
          display: flex;
          // flex-direction: row;
          // align-items: center;
          position: relative;

          // 隐藏未选中图标
          .van-radio__icon:not(.van-radio__icon--checked) {
            display: none;
          }
          
          // 调整选中图标位置
          // .van-radio__icon--checked {
          //   position: absolute;
          //   top: 5px;
          //   right: 5px;
          //   z-index: 99;
          //   font-size: 30rpx !important;
          // }

          .van-radio__icon{
            position: absolute;
            top: 0px;
            right: 0px;
            z-index: 99;
            font-size: 30rpx;
          }
          .van-radio__label {
            margin-right: 0;
            // display: flex;
            // flex-direction: column;
            // align-items: center;
          }
        }
       .images {
          // width: 100%;
          height: 180rpx;
          width: 180rpx;
          background: #fff;
          position: relative;

          .van-image {
            // 确保图片填充容器
            width: 100%;
            height: 100%;
            // 添加图片缩放效果
            transition: transform 0.3s ease;
            
            &:hover {
              transform: scale(1.01);
              opacity: 0.7;
            }
          }
          .image-item {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
          }
        }

        .title {
          // white-space: wrap;
          // // width: 200rpx;
          // font-size: 24rpx;
          // // margin: 17rpx;
          // flex-shrink: 0;
          // flex-grow: 0;
          // height: 50rpx;
          // // line-height: 50rpx;
          // line-height: 35rpx;

          // 新增：限制最大宽度并添加优雅的文本溢出处理
          max-width: 160rpx;
          white-space: pre-wrap; // 允许换行
          word-break: break-all; // 允许单词内断行
    
          height: auto !important;
          padding: 8rpx;
          font-size: 24rpx;
          line-height: 1.5;
          padding: 4rpx 8rpx;
          color: #666;
          text-align: center;
          // 添加文字溢出处理
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          // 添加背景和间距
          background: #fff;
          margin-top: 10rpx;
          border-radius: 4px;
        }
      }
    }

    // .custom-scroll-x {//隐藏滚动条样式
    //   z-index: 999;
    //   overflow-x: auto;
    //   // -ms-overflow-style: none; /* IE/Edge */
    //   // scrollbar-width: none; /* Firefox */
      
    //   // &::-webkit-scrollbar {
    //   //   display: none; /* Chrome/Safari/Opera */
    //   // }
  
    //   // 保持原有flex布局
    //   .flex {
    //     // display: flex;
    //     display: inline-flex;  // 行内flex布局
    //     min-width: max-content;  // 强制保持内容宽度
    //     white-space: nowrap;  // 禁止换行
    //   }
    // }

    // .material-scroll {
    //   display: flex;

    //   .material-item {
    //     // height: 280rpx;
    //     // width: 25vw;
    //     // background-color: #fff;
    //     // border-radius: 17rpx;
    //     // //overflow: hidden;
    //     // display: flex;
    //     // flex-direction: column;
    //     // position: relative;
    //     // margin-right: 30rpx;
    //     // text-align: center;
    //     // flex-shrink: 0;

    //     &.active {
    //       opacity: 0.7;

    //       .radio {
    //         position: absolute;
    //         right: 17rpx;
    //         top: 17rpx;
    //         z-index: 1;
    //       }
    //     }

    //     .image {
    //       width: 100%;
    //       height: 280rpx;
    //       background: #fff;
    //       position: relative;

    //       image {
    //         width: 100%;
    //         height: 100%;
    //         position: absolute;
    //         top: 0;
    //         left: 0;
    //       }
    //     }

    //     .title {
    //       // width: 200rpx;
    //       font-size: 24rpx;
    //       // margin: 17rpx;
    //       flex-shrink: 0;
    //       flex-grow: 0;
    //       height: 50rpx;
    //       // line-height: 50rpx;
    //       line-height: 40rpx;
    //     }

    //     .item-btn {
    //       height: 65.8rpx;
    //       border-radius: 17rpx;
    //       font-size: 30rpx;
    //       box-sizing: border-box;
    //       text-align: center;
    //       line-height: 62.8rpx;
    //       background-color: #333;
    //       color: #fff;
    //       margin: 17rpx;
    //     }
    //   }
    // }
  }
}

@media (min-width: 1024px) {
  .example {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>
